<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017-9-13
 * Time: 10:15
 */

Yaf_Loader::import(EXTEND_PATH.'/qsms/Sms.php');

class Controller extends Yaf_Controller_Abstract
{
    protected $key='Train-WWW';
    /**
     * 登录验证
     */
    public function authentication()
    {
        $session = Yaf_Session::getInstance();
        if(!empty($session->token)){
            $key = $this->passport_decrypt($session->token);
            $redis = Yaf_Registry::get('redis');
            $jsToken = json_decode($redis->hget('User',$key),true);
            if($jsToken['token'] == $session->token) {
                return $jsToken;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 数据返回
     */
    public function returnApi($data = [], $code = 100, $content = [])
    {
        unset($content['s']);
        $result = [
            'data' => $data,
            'code' => $code,
            'time' => $_SERVER['REQUEST_TIME'],
            'content'  => $content,
        ];
        Log::write(json_encode($result),'info');
        echo json_encode($result);
        Yaf_Dispatcher::getInstance()->disableView();
    }

    /**
     * token生成
     */
    public function tokenProduce($name, $content = [])
    {
        if($name){
            $token = $this->passport_encrypt($name);
            $redis = Yaf_Registry::get('redis');
            $content['token'] = $token;
            $redis->hdel('User',$name);
            $redis->hset('User',$name, json_encode($content));
        }else{
            $token = NULL;
        }
        return $token;
    }

    /**
     * 功能：对字符串进行加密处理
     * @param string $str
     * 需要加密的内容.
     * @return string
     * 加密后的内容
     */
    private function passport_encrypt($str)
    {
        srand((double)microtime() * 1000000);
        $encrypt_key=md5(rand(0, 32000));
        $ctr=0;
        $tmp='';
        for($i=0;$i<strlen($str);$i++){
            $ctr=$ctr==strlen($encrypt_key)?0:$ctr;
            $tmp.=$encrypt_key[$ctr].($str[$i] ^ $encrypt_key[$ctr++]);
        }
        return base64_encode($this->passport_key($tmp,$this->key));
    }

    /**
     * 功能：对字符串进行解密处理
     * @param string $str
     * 需要解密的密文.
     * @return string
     * 解出的内容
     */
    private function passport_decrypt($str)
    {
        $str=$this->passport_key(base64_decode($str),$this->key);
        $tmp='';
        for($i=0;$i<strlen($str);$i++){
            $md5=$str[$i];
            $tmp.=$str[++$i] ^ $md5;
        }
        return $tmp;
    }

    /**
     *辅助函数
     */
    private function passport_key($str,$encrypt_key)
    {
        $encrypt_key=md5($encrypt_key);
        $ctr=0;
        $tmp='';
        for($i=0;$i<strlen($str);$i++){
            $ctr=$ctr==strlen($encrypt_key)?0:$ctr;
            $tmp.=$str[$i] ^ $encrypt_key[$ctr++];
        }
        return $tmp;
    }

    /**
     * 过滤表情
     */
    function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

        return $str;
    }

    /**
     * 生成验证码并返回
     *
     * @param string $phone 需要的手机号
     */
    public function verifyCode($phone)
    {
        $redis = Yaf_Registry::get('redis');
        $jsCode = json_decode($redis->hget('Code',$phone),true);
        if($jsCode['time']+300 > time()){
            $msg['message'] = '验证码已下发，请耐心等待';
            $msg['code'] = 200;
        }else{
            $code = rand(1000,9999);
            $redis->hdel('Code',$phone);
            $redis->hset('Code',$phone, json_encode(['code'=>$code,'time'=>time()]));
            $message['content'] = '您本次操作的验证码是:'.$code.'您可千万不要不告诉任何人哦.目前还没有客服热线呐';
            $message['phone'] = $phone;
            $send = $this->bindipSend($message);
            if($send['code']){
                $send = $this->qSms($message);
                if($send['result']){
                    $msg['message'] = '短信下发失败';
                    $msg['bami'] = $send['msg'];
                    $msg['tencent'] = $send['errmsg'];
                    $msg['code'] = 400;
                }else{
                    $msg['message'] = '验证码通过腾讯云下发，请注意查收';
                    $msg['code'] = 200;
                }
            }else{
                $msg['message'] = '验证码通过八米科技下发，请注意查收';
                $msg['code'] = 200;
            }
        }
        return $msg;
    }

    /**
     * 获取客户端IP地址
     * @param integer   $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param boolean   $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    public function ip($type = 0, $adv = false)
    {
        $type      = $type ? 1 : 0;
        static $ip = null;
        if (null !== $ip) {
            return $ip[$type];
        }

        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }
                $ip = trim(current($arr));
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip   = $long ? [$ip, $long] : ['0.0.0.0', 0];
        return $ip[$type];
    }

    /**
     * 短信下发
     */
    public function bindipSend($data)
    {
        $data = [
            'uid'=>1236,
            'passwd'=>'6fb643529d8aff2c9f86d1af722a0759',
            'phonelist'=>$data['phone'],
            'content'=>$data['content'].'【天满星科技】'
        ];
        $result = $this->httpPost('http://sms.bamikeji.com:8890/mtPort/mt/bindip/send', $data);
        if ($result) {
            $json = json_decode($result, true);
            return $json;
        }
        return false;
    }

    /**
     * 短信下发
     */
    public function qSms($data)
    {
        $qSms = new Sms();
        $result = $qSms ->SingleSender($data['phone'],$data['content']);
        if ($result) {
            $json = json_decode($result, true);
            return $json;
        }
        return false;
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    public function httpPost($url,$param,$post_file=false){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
}